package dianmobile.eistarandroid.ui.Adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.beans.BoardItemEntity;
import dianmobile.eistarandroid.network.request.BookBoardRequest;
import dianmobile.eistarandroid.network.request.RequestCallback;
import dianmobile.eistarandroid.network.request.RequestType;
import dianmobile.eistarandroid.utils.ConstantsData;

public class BoardListAdapter extends BaseAdapter implements Filterable{

    private List<BoardItemEntity> boardItemListData;
    private Context context;
    private LayoutInflater mInflater;
    private Filter filter;
    final private List<BoardItemEntity> originData;

    public BoardListAdapter(Context context, List<BoardItemEntity> data) {
        this.context = context;
        this.boardItemListData = data;
        originData = data;
        Log.d("board", "originData = data");
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return boardItemListData.size();
    }

    @Override
    public Object getItem(int position) {
        return boardItemListData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BoardItemEntity entity = boardItemListData.get(position);

        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.sub_board_item, null);

            viewHolder = new ViewHolder();
            viewHolder.tvNameEN = (TextView)convertView.findViewById(R.id.tv_board_name_en);
            viewHolder.tvNameCN = (TextView)convertView.findViewById(R.id.tv_board_name_cn);
            viewHolder.isBookTagIv = (ImageView) convertView.findViewById(R.id.iv_board_bookmark);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //set the view
        viewHolder.tvNameCN.setText(entity.getBoardTitle());
        if(entity.isHasRead()) {
            viewHolder.tvNameEN.setAlpha((float)0.54);
        } else {
            viewHolder.tvNameEN.setAlpha((float)1);
        }
        viewHolder.tvNameEN.setText(entity.getBoardName());
        viewHolder.isBookmark = entity.isBookmark();
        if ( viewHolder.isBookmark) {
            viewHolder.isBookTagIv.setImageResource(R.drawable.ic_bookmark_yellow);
        }else {
            viewHolder.isBookTagIv.setImageResource(R.drawable.ic_bookmark_gray);
        }

        viewHolder.isBookTagIv.setOnClickListener(new myClickListener(entity, viewHolder));

        return convertView;
    }

    @Override
    public Filter getFilter() {
        if(filter == null) {
            filter = new myFilter();
        }
        return filter;
    }

    private static class ViewHolder {
        public TextView tvNameEN;
        public TextView tvNameCN;
        public boolean isBookmark = false;
        public ImageView isBookTagIv;
    }

    /**
     * autocompleteTextView用到的自定义filter
     */
    class myFilter extends Filter{
        //TODO 只能过滤一次 第二次搜索就没有结果，除非关掉搜索框重开---因为originData被清空了
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            FilterResults results = new FilterResults();
            List<BoardItemEntity> values = new ArrayList<>();   //匹配的结果集
            Log.d("board", "performFiltering: size: " + originData.size() + " charis: " + charSequence);
            for(int i = 0; i < originData.size(); i++){
                if( charSequence!=null
                        && (originData.get(i).getBoardName().contains(charSequence)
                        || originData.get(i).getBoardTitle().contains(charSequence))){
                    values.add(originData.get(i));
                }
            }
            results.values = values;
            results.count = values.size();
            return results;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            if(filterResults.count > 0) {
                boardItemListData.clear();
                boardItemListData = (List<BoardItemEntity>) filterResults.values;
                notifyDataSetChanged();
            }
        }
    }

    private class myClickListener implements View.OnClickListener {

        private BoardItemEntity entity;
        private ViewHolder viewHolder;
        public myClickListener(BoardItemEntity entity, ViewHolder viewHolder) {
            this.entity = entity;
            this.viewHolder = viewHolder;
        }

        @Override
        public void onClick(View v) {
            Map<String, String> params = new HashMap<>();
            params.put(ConstantsData.EXTRA_BOARD_NAME, entity.getBoardName());
            if(entity.isBookmark()){

                BookBoardRequest.execute(context, RequestType.UN_BOOK_BOARD, params, new RequestCallback() {
                    @Override
                    public void onResult(Map<String, Object> result, String error) {
                        if (error != null) {
                            Toast.makeText(context, "网络错误", Toast.LENGTH_SHORT).show();
                        } else {
                            if (result.containsKey(ConstantsData.ERROR_RESULT) ) {
                                Toast.makeText(context, (String)result.get(ConstantsData.ERROR_RESULT), Toast.LENGTH_SHORT).show();
                            } else {
                                entity.setIsBookmark(false);
                                viewHolder.isBookmark = false;
                                Toast.makeText(context, entity.getBoardTitle() + ": 取消订阅成功", Toast.LENGTH_SHORT).show();

                                viewHolder.isBookTagIv.setImageResource(R.drawable.ic_bookmark_gray);
                            }

                        }
                    }
                });
            }else{
                BookBoardRequest.execute(context, RequestType.BOOK_BOARD, params, new RequestCallback() {
                    @Override
                    public void onResult(Map<String, Object> result, String error) {
                        if (error != null) {
                            Toast.makeText(context, "网络错误", Toast.LENGTH_SHORT).show();
                        } else {
                            if (result.containsKey(ConstantsData.ERROR_RESULT) ) {
                                Toast.makeText(context, (String)result.get(ConstantsData.ERROR_RESULT), Toast.LENGTH_SHORT).show();
                            } else {
                                entity.setIsBookmark(true);
                                viewHolder.isBookmark = true;
                                Toast.makeText(context, entity.getBoardTitle() + ": 订阅成功", Toast.LENGTH_SHORT).show();
                                viewHolder.isBookTagIv.setImageResource(R.drawable.ic_bookmark_yellow);
                            }
                        }
                    }
                });
            }
        }
    }

}

